<!-- 仅修改template和style部分 -->
<template>
  <!-- 仅修改class名称，保持所有数据绑定 -->
  <div class="mobile-login">
    <div class="form-wrapper">
      <h1 class="system-name">寝迹管理</h1>

      <el-form
          ref="loginRef"
          :model="loginForm"
          :rules="loginRules"
          @submit.prevent="handleLogin"
          class="auth-form">

        <!-- 用户名输入（保持v-model绑定） -->
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入账号"
              :prefix-icon="User"
              size="large"
              class="rounded-input"
          />
        </el-form-item>

        <!-- 密码输入（保持type和show-password） -->
        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
              size="large"
              class="rounded-input"
          />
        </el-form-item>

        <!-- 验证码区域（保持v-if条件） -->
        <el-form-item v-if="captchaEnabled" prop="code">
          <div class="captcha-area">
            <el-input
                v-model="loginForm.code"
                placeholder="验证码"
                :prefix-icon="Picture"
                size="large"
                class="rounded-input input-with-captcha"
            />
            <img
                :src="codeUrl"
                @click="getCode"
                class="captcha-image"
                alt="点击刷新验证码"
            />
          </div>
        </el-form-item>

        <!-- 记住密码（保持v-model绑定） -->
        <el-checkbox v-model="loginForm.rememberMe" class="remember-check">
          记住密码
        </el-checkbox>

        <!-- 登录按钮（保持loading状态） -->
        <el-button
            native-type="submit"
            :loading="loading"
            type="primary"
            size="large"
            class="submit-btn"
        >
          {{ loading ? '登录中...' : '立即登录' }}
        </el-button>

        <!-- 注册链接（保持v-if条件） -->
        <div v-if="register" class="register-tip">
          <router-link to="/register">没有账号？立即注册</router-link>
        </div>
      </el-form>
    </div>

    <!-- 底部信息（保持原有内容） -->
    <footer class="footer-info">
      <span>Copyright © 2018-2025 dm.vip</span>
    </footer>
  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: ""
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        router.push({ path: redirect.value || "/", query: otherQueryParams });
      }).catch(() => {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode();
        }
      });
    }
  });
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

getCode();
getCookie();
</script>


<style lang="scss" scoped>
/* 移动端优化样式 */
.mobile-login {
  min-height: 100vh;
  padding: 1rem;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.form-wrapper {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 2rem 1.5rem;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
  backdrop-filter: blur(4px);
}

.system-name {
  color: #2c3e50;
  font-size: 1.75rem;
  text-align: center;
  margin: 0 0 2.5rem;
  font-weight: 600;
  letter-spacing: 1px;
}

.auth-form {
  :deep(.el-form-item) {
    margin-bottom: 1.75rem;

    &.is-error .el-input__wrapper {
      box-shadow: 0 0 0 1px var(--el-color-danger) inset;
    }
  }
}

.rounded-input {
  :deep(.el-input__wrapper) {
    border-radius: 12px;
    padding: 0.875rem 1.25rem;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    }
  }
}
.input-with-captcha {
  flex: 1;
}
.captcha-area {
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 5rch; /* 元素间距 */

  .captcha-image {
    height: 60px;

    border-radius: 8px;
    border: 1px solid #e0e0e0;
    cursor: pointer;
    transition: transform 0.2s;

    &:active {
      transform: scale(0.98);
    }
  }
}

.remember-check {
  margin: 1rem 0 2rem;
  color: #666;
}

.submit-btn {
  width: 100%;
  border-radius: 12px;
  height: 56px;
  font-size: 1.125rem;
  letter-spacing: 1px;
  transition: all 0.3s ease;

  &:not(.is-loading):hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  }
}

.register-tip {
  text-align: center;
  margin-top: 1.5rem;

  a {
    color: #409eff;
    font-size: 0.95rem;
    font-weight: 500;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

.footer-info {
  text-align: center;
  color: #95a5a6;
  font-size: 0.85rem;
  padding: 2rem 0 1rem;
}

@media (max-width: 480px) {
  .form-wrapper {
    padding: 1.5rem 1rem;
  }

  .system-name {
    font-size: 1.5rem;
    margin-bottom: 2rem;
  }

  .rounded-input :deep(.el-input__wrapper) {
    padding: 0.75rem 1rem;
  }
}
</style>
